<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { SidebarTrigger } from '@/components/ui/sidebar'
import axios from 'axios'

// 定义帖子接口类型
interface Post {
  id: number
  title: string
  content: string
  author: string
  timestamp: string
  replies: number
}

// 定义回复接口类型
interface Reply {
  id: number
  content: string
  author: string
  timestamp: string
  postId: number
}

// 路由
const router = useRouter()

// 响应式数据
const posts = ref<Post[]>([])
const showNewPost = ref(false)
const newPost = ref({ title: '', content: '', author: '' })
const loading = ref(false)
const error = ref('')
const expandedPosts = ref<Set<number>>(new Set())
const replies = ref<Record<number, Reply[]>>({})
const newReply = ref<Record<number, { content: string, author: string }>>({})
const replyLoading = ref<Record<number, boolean>>({})

// API基础URL
const API_BASE_URL = 'http://localhost:8081/api'

// 格式化时间戳
const formatTimestamp = (timestamp: string) => {
  const date = new Date(timestamp)
  const now = new Date()
  const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000)
  
  if (diffInSeconds < 60) {
    return '刚刚'
  } else if (diffInSeconds < 3600) {
    const minutes = Math.floor(diffInSeconds / 60)
    return `${minutes}分钟前`
  } else if (diffInSeconds < 86400) {
    const hours = Math.floor(diffInSeconds / 3600)
    return `${hours}小时前`
  } else if (diffInSeconds < 604800) {
    const days = Math.floor(diffInSeconds / 86400)
    return `${days}天前`
  } else {
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    })
  }
}

// 获取帖子列表
const fetchPosts = async () => {
  try {
    loading.value = true
    error.value = ''
    const response = await axios.get('http://localhost:8081/api/posts')
    posts.value = response.data
    
    // 保存帖子数据到localStorage，供PostDetails组件使用
    localStorage.setItem('forum_posts', JSON.stringify(posts.value))
  } catch (err) {
    error.value = '获取帖子失败，请重试'
    console.error('获取帖子失败:', err)
  } finally {
    loading.value = false
  }
}

// 提交新帖子
const handleSubmitPost = async (e: Event) => {
  e.preventDefault()
  if (newPost.value.title && newPost.value.content && newPost.value.author) {
    try {
      loading.value = true
      error.value = ''
      const response = await axios.post(`${API_BASE_URL}/posts`, {
        title: newPost.value.title,
        content: newPost.value.content,
        author: newPost.value.author
      })
      
      // 添加新帖子到列表顶部
      posts.value.unshift(response.data)
      
      // 更新localStorage中的帖子数据
      localStorage.setItem('forum_posts', JSON.stringify(posts.value))
      
      // 重置表单
      newPost.value = { title: '', content: '', author: '' }
      showNewPost.value = false
    } catch (err) {
      error.value = '发布帖子失败，请重试'
      console.error('发布帖子失败:', err)
    } finally {
      loading.value = false
    }
  }
}

// 生成唯一ID
let replyIdCounter = 1

// 切换帖子回复显示
const toggleReplies = (postId: number) => {
  if (expandedPosts.value.has(postId)) {
    expandedPosts.value.delete(postId)
  } else {
    expandedPosts.value.add(postId)
    // 如果还没有回复数组，初始化为空数组
    if (!replies.value[postId]) {
      replies.value[postId] = []
    }
  }
}

// 提交回复（纯前端实现）
const submitReply = (postId: number) => {
  const replyData = newReply.value[postId]
  if (!replyData || !replyData.content || !replyData.author) {
    return
  }
  
  // 模拟加载状态
  replyLoading.value[postId] = true
  
  setTimeout(() => {
    // 创建新回复对象
    const newReplyObj: Reply = {
      id: replyIdCounter++,
      content: replyData.content,
      author: replyData.author,
      timestamp: new Date().toISOString(),
      postId: postId
    }
    
    // 添加新回复到列表
    if (!replies.value[postId]) {
      replies.value[postId] = []
    }
    replies.value[postId].push(newReplyObj)
    
    // 更新帖子回复数量
    const post = posts.value.find(p => p.id === postId)
    if (post) {
      post.replies += 1
    }
    
    // 重置回复表单
    newReply.value[postId] = { content: '', author: '' }
    replyLoading.value[postId] = false
  }, 500) // 模拟网络延迟
}

// 初始化回复表单
const initReplyForm = (postId: number) => {
  if (!newReply.value[postId]) {
    newReply.value[postId] = { content: '', author: '' }
  }
}

// 查看帖子详情
const viewPostDetails = (postId: number) => {
  router.push(`/posts/${postId}`)
}

// 组件挂载时获取帖子数据
onMounted(() => {
  fetchPosts()
})
</script>

<template>
  <div class="page">
  
    <!-- 头部导航 -->
    <header class="header">
      <SidebarTrigger />
      <h1>帖子</h1>
      <div class="header-actions">
        <button 
          class="new-post-btn"
          @click="showNewPost = !showNewPost"
        >
          {{ showNewPost ? '取消发帖' : '发新帖' }}
        </button>
      </div>
    </header>

    <main class="content">
      <!-- 错误提示 -->
      <div v-if="error" class="error-message">
        {{ error }}
        <button @click="fetchPosts" class="retry-btn">重试</button>
      </div>

      <!-- 发帖表单 -->
      <div v-if="showNewPost" class="new-post-form">
        <h3>发表新帖</h3>
        <form @submit="handleSubmitPost">
          <input
            type="text"
            placeholder="帖子标题"
            v-model="newPost.title"
            :disabled="loading"
            required
          />
          <input
            type="text"
            placeholder="作者昵称"
            v-model="newPost.author"
            :disabled="loading"
            required
          />
          <textarea
            placeholder="帖子内容"
            v-model="newPost.content"
            :disabled="loading"
            required
          ></textarea>
          <button type="submit" :disabled="loading">
            {{ loading ? '发布中...' : '发布帖子' }}
          </button>
        </form>
      </div>

      <!-- 帖子列表 -->
      <div class="posts-list">
        <h2>最新帖子</h2>
        
        <!-- 加载状态 -->
        <div v-if="loading && posts.length === 0" class="loading">
          正在加载帖子...
        </div>
        
        <!-- 空状态 -->
        <div v-else-if="!loading && posts.length === 0 && !error" class="empty-state">
          暂无帖子，快来发布第一个帖子吧！
        </div>
        
        <!-- 帖子列表 -->
        <div v-for="post in posts" :key="post.id" class="post-card">
          <div class="post-header">
            <h3>{{ post.title }}</h3>
            <span class="post-meta">
              {{ post.author }} • {{ formatTimestamp(post.timestamp) }}
            </span>
          </div>
          <p class="post-content">{{ post.content }}</p>
          <div class="post-footer">
            <span class="replies-count">💬 {{ post.replies }} 回复</span>
            <button class="reply-btn" @click="viewPostDetails(post.id)">
              查看详情
            </button>
          </div>
          
          <!-- 回复区域 -->
          <div v-if="expandedPosts.has(post.id)" class="replies-section">
            <!-- 回复列表 -->
            <div v-if="replies[post.id] && replies[post.id].length > 0" class="replies-list">
              <div v-for="reply in replies[post.id]" :key="reply.id" class="reply-item">
                <div class="reply-header">
                  <span class="reply-author">{{ reply.author }}</span>
                  <span class="reply-time">{{ formatTimestamp(reply.timestamp) }}</span>
                </div>
                <p class="reply-content">{{ reply.content }}</p>
              </div>
            </div>
            
            <!-- 无回复提示 -->
            <div v-else class="no-replies">
              暂无回复，快来抢沙发吧！
            </div>
            
            <!-- 回复表单 -->
            <div class="reply-form">
              <h4>发表回复</h4>
              <input
                 type="text"
                 placeholder="你的昵称"
                 :value="newReply[post.id]?.author || ''"
                 @input="(e) => { initReplyForm(post.id); newReply[post.id].author = e.target.value }"
                 @focus="initReplyForm(post.id)"
                 :disabled="replyLoading[post.id]"
                 required
               />
               <textarea
                 placeholder="写下你的回复..."
                 :value="newReply[post.id]?.content || ''"
                 @input="(e) => { initReplyForm(post.id); newReply[post.id].content = e.target.value }"
                 @focus="initReplyForm(post.id)"
                 :disabled="replyLoading[post.id]"
                 required
               ></textarea>
              <button 
                @click="submitReply(post.id)"
                :disabled="replyLoading[post.id] || !newReply[post.id]?.content || !newReply[post.id]?.author"
                class="submit-reply-btn"
              >
                {{ replyLoading[post.id] ? '发布中...' : '发布回复' }}
              </button>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>
<style scoped>
.page {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: hsl(var(--background));
  color: hsl(var(--foreground));
}

.dark .page {
  background-color: #111318;
}

.content {
  flex: 1;
  padding: 2rem;
  background-color: hsl(var(--background));
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
}

.dark .content {
  background-color: #14151d;
}

/* 头部导航样式 */
.header {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem 2rem;
  border-bottom: 1px solid hsl(var(--sidebar-border));
  background: hsl(var(--sidebar-background));
  color: hsl(var(--sidebar-foreground));
}

.header h1 {
  margin: 0;
  font-size: 1.5rem;
  font-weight: 600;
  color: hsl(var(--sidebar-foreground));
  flex: 1;
}

.header-actions {
  margin-left: auto;
}

.new-post-btn {
  background: hsl(var(--primary));
  color: hsl(var(--primary-foreground));
  border: 2px solid hsl(var(--primary));
  padding: 0.5rem 1rem;
  border-radius: 25px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s ease;
}

.new-post-btn:hover {
  background: hsl(var(--primary) / 0.9);
  transform: translateY(-2px);
}

/* 主要内容区域 */
main {
  padding: 2rem 0;
}

/* 发帖表单样式 */
.new-post-form {
  background: hsl(var(--card));
  padding: 2rem;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0,0,0,0.1);
  margin-bottom: 2rem;
  border: 1px solid hsl(var(--border));
}

.dark .new-post-form {
  background-color: #1e2022;
}

/* 错误提示样式 */
.error-message {
  background: #fee2e2;
  color: #dc2626;
  padding: 1rem;
  border-radius: 8px;
  margin-bottom: 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border: 1px solid #fecaca;
}

.dark .error-message {
  background: #7f1d1d;
  color: #fca5a5;
  border-color: #991b1b;
}

.retry-btn {
  background: #dc2626;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 6px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: background 0.3s ease;
}

.retry-btn:hover {
  background: #b91c1c;
}

/* 加载状态样式 */
.loading {
  text-align: center;
  padding: 2rem;
  color: hsl(var(--muted-foreground));
  font-size: 1.1rem;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 3rem;
  color: hsl(var(--muted-foreground));
  font-size: 1.1rem;
  background: hsl(var(--card));
  border-radius: 12px;
  border: 1px solid hsl(var(--border));
}

.dark .empty-state {
  background-color: #1e2022;
}

/* 禁用状态样式 */
.new-post-form input:disabled,
.new-post-form textarea:disabled,
.new-post-form button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.new-post-form h3 {
  color: hsl(var(--foreground));
  margin-bottom: 1.5rem;
  font-size: 1.3rem;
}

.new-post-form form {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.new-post-form input,
.new-post-form textarea {
  padding: 0.75rem;
  border: 2px solid hsl(var(--border));
  border-radius: 8px;
  font-size: 1rem;
  background: hsl(var(--background));
  color: hsl(var(--foreground));
  transition: border-color 0.3s ease;
}

.new-post-form input:focus,
.new-post-form textarea:focus {
  outline: none;
  border-color: hsl(var(--primary));
}

.new-post-form textarea {
  min-height: 120px;
  resize: vertical;
}

.new-post-form button {
  background: hsl(var(--primary));
  color: hsl(var(--primary-foreground));
  border: none;
  padding: 0.75rem 2rem;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.new-post-form button:hover {
  background: hsl(var(--primary) / 0.9);
  transform: translateY(-2px);
}

/* 帖子列表样式 */
.posts-list h2 {
  color: hsl(var(--foreground));
  margin-bottom: 1.5rem;
  font-size: 1.5rem;
  visibility: hidden;  /* 隐藏文字但保留空间 */
}

.post-card {
  background: hsl(var(--card));
  border-radius: 12px;
  padding: 1.5rem;
  margin-bottom: 1.5rem;
  box-shadow: 0 2px 15px rgba(0,0,0,0.08);
  border: 1px solid hsl(var(--border));
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.dark .post-card {
  background-color: #1e2022;
}

.post-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 25px rgba(0,0,0,0.15);
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 1rem;
}

.post-header h3 {
  color: hsl(var(--foreground));
  font-size: 1.2rem;
  margin: 0;
  flex: 1;
  font-weight: bold;  /* 添加这一行来让标题加粗 */
}

.post-meta {
  color: hsl(var(--muted-foreground));
  font-size: 0.9rem;
  white-space: nowrap;
  margin-left: 1rem;
}

.post-content {
  color: hsl(var(--foreground));
  line-height: 1.6;
  margin-bottom: 1rem;
}

.post-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 1rem;
  border-top: 1px solid hsl(var(--border));
}

.replies-count {
  color: hsl(var(--muted-foreground));
  font-size: 0.9rem;
}

.reply-btn {
  background: hsl(var(--secondary));
  color: hsl(var(--secondary-foreground));
  border: 1px solid hsl(var(--border));
  padding: 0.4rem 1rem;
  border-radius: 20px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: all 0.3s ease;
}

.reply-btn:hover {
  background: hsl(var(--primary));
  color: hsl(var(--primary-foreground));
  transform: translateY(-1px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .container {
    padding: 0 15px;
  }
  
  .forum-header .container {
    flex-direction: column;
    gap: 1rem;
    text-align: center;
  }
  
  .post-header {
    flex-direction: column;
    gap: 0.5rem;
  }
  
  .post-meta {
    margin-left: 0;
  }
  
  .post-footer {
    flex-direction: column;
    gap: 0.5rem;
    align-items: flex-start;
  }
}

/* 回复区域样式 */
.replies-section {
  margin-top: 1rem;
  padding-top: 1rem;
  border-top: 1px solid hsl(var(--border));
}

.replies-list {
  margin-bottom: 1.5rem;
}

.reply-item {
  background: hsl(var(--muted) / 0.3);
  border-radius: 8px;
  padding: 1rem;
  margin-bottom: 0.75rem;
  border-left: 3px solid hsl(var(--primary));
}

.dark .reply-item {
  background-color: rgba(255, 255, 255, 0.05);
}

.reply-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
}

.reply-author {
  font-weight: 600;
  color: hsl(var(--primary));
  font-size: 0.9rem;
}

.reply-time {
  color: hsl(var(--muted-foreground));
  font-size: 0.8rem;
}

.reply-content {
  color: hsl(var(--foreground));
  line-height: 1.5;
  margin: 0;
  font-size: 0.95rem;
}

.no-replies {
  text-align: center;
  color: hsl(var(--muted-foreground));
  font-style: italic;
  padding: 1rem;
  margin-bottom: 1rem;
}

.reply-form {
  background: hsl(var(--muted) / 0.2);
  border-radius: 8px;
  padding: 1.5rem;
  border: 1px solid hsl(var(--border));
}

.dark .reply-form {
  background-color: rgba(255, 255, 255, 0.03);
}

.reply-form h4 {
  color: hsl(var(--foreground));
  margin: 0 0 1rem 0;
  font-size: 1.1rem;
}

.reply-form input,
.reply-form textarea {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid hsl(var(--border));
  border-radius: 6px;
  font-size: 0.95rem;
  background: hsl(var(--background));
  color: hsl(var(--foreground));
  margin-bottom: 0.75rem;
  transition: border-color 0.3s ease;
  box-sizing: border-box;
}

.reply-form input:focus,
.reply-form textarea:focus {
  outline: none;
  border-color: hsl(var(--primary));
}

.reply-form textarea {
  min-height: 80px;
  resize: vertical;
}

.submit-reply-btn {
  background: hsl(var(--primary));
  color: hsl(var(--primary-foreground));
  border: none;
  padding: 0.6rem 1.5rem;
  border-radius: 6px;
  font-size: 0.9rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.submit-reply-btn:hover:not(:disabled) {
  background: hsl(var(--primary) / 0.9);
  transform: translateY(-1px);
}

.submit-reply-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

/* 回复区域响应式设计 */
@media (max-width: 768px) {
  .reply-item {
    padding: 0.75rem;
  }
  
  .reply-form {
    padding: 1rem;
  }
  
  .reply-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.25rem;
  }
}
</style>
